/**
 * ResizeHandle - Draggable handle for resizing panels
 * 
 * Features:
 * - Horizontal/vertical resize
 * - Visual feedback on hover/drag
 * - Touch support
 */

import { useState, useEffect, useRef } from 'react';
import { GripVertical } from 'lucide-react';
import { cn } from '@/lib/utils';

interface ResizeHandleProps {
  onResize: (delta: number) => void;
  direction?: 'horizontal' | 'vertical';
  className?: string;
}

export function ResizeHandle({
  onResize,
  direction = 'horizontal',
  className
}: ResizeHandleProps) {
  const [isDragging, setIsDragging] = useState(false);
  const startPosRef = useRef(0);

  useEffect(() => {
    if (!isDragging) return;

    const handleMouseMove = (e: MouseEvent) => {
      const delta = direction === 'horizontal' 
        ? e.clientX - startPosRef.current
        : e.clientY - startPosRef.current;
      
      startPosRef.current = direction === 'horizontal' ? e.clientX : e.clientY;
      onResize(delta);
    };

    const handleMouseUp = () => {
      setIsDragging(false);
    };

    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);

    return () => {
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
    };
  }, [isDragging, direction, onResize]);

  const handleMouseDown = (e: React.MouseEvent) => {
    e.preventDefault();
    setIsDragging(true);
    startPosRef.current = direction === 'horizontal' ? e.clientX : e.clientY;
  };

  const handleTouchStart = (e: React.TouchEvent) => {
    const touch = e.touches[0];
    setIsDragging(true);
    startPosRef.current = direction === 'horizontal' ? touch.clientX : touch.clientY;
  };

  return (
    <div
      className={cn(
        'group relative flex items-center justify-center transition-colors',
        direction === 'horizontal'
          ? 'w-1 cursor-ew-resize hover:w-1.5'
          : 'h-1 cursor-ns-resize hover:h-1.5',
        isDragging
          ? 'bg-primary'
          : 'bg-transparent hover:bg-border',
        className
      )}
      onMouseDown={handleMouseDown}
      onTouchStart={handleTouchStart}
      role="separator"
      aria-orientation={direction}
    >
      {/* Visual indicator */}
      <div
        className={cn(
          'absolute flex items-center justify-center',
          'opacity-0 group-hover:opacity-100 transition-opacity',
          direction === 'horizontal'
            ? 'inset-y-0 w-4 -left-1.5'
            : 'inset-x-0 h-4 -top-1.5',
          isDragging && 'opacity-100'
        )}
      >
        <GripVertical 
          className={cn(
            'w-3 h-3 text-muted-foreground',
            direction === 'vertical' && 'rotate-90'
          )}
        />
      </div>
    </div>
  );
}

